package com.backend.web.weixin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.backend.config.WxConfig;
import com.backend.constants.WxConstant;
import com.backend.utils.HttpUtil;
import com.backend.utils.WxCryptUtils;
import com.backend.web.system.entity.User;
import com.backend.web.system.service.IUserService;
import com.backend.web.weixin.service.IWxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author HUJIAMIN
 * @since 2020/11/7
 */
@Service
public class WxServiceImpl implements IWxService {

  @Autowired
  private WxConfig wxConfig;
  @Autowired
  private IUserService userService;

  @Override
  public JSONObject code2Session(String code) {
    String url = String
      .format(WxConstant.WX_URL_FORMAT, wxConfig.getAppid(), wxConfig.getSecret(), code);
    try {
      String res = HttpUtil.get(url);
      return JSONObject.parseObject(res);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new JSONObject();
  }

  @Override
  public JSONObject getUserInfo(JSONObject json) {
    // 需要加密的数据
    String encryptedData = json.getString("encryptedData");
    String iv = json.getString("iv");
    String sessionKey = json.getString("session_key");
    String openId = json.getString("openid");
    try {
      String data = WxCryptUtils.decrypt(encryptedData, iv, sessionKey);

      JSONObject result = JSON.parseObject(data);
      String phone = result.getString("purePhoneNumber");
      userService.addUser(openId, phone);
      return result;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new JSONObject();
  }

  @Override
  public JSONObject loginByCode(JSONObject json) {
    String code = json.getString("code");

    String userId = json.getString("userId");
    JSONObject result = new JSONObject();
    if (StrUtil.isNotBlank(userId)) {
      User user = userService.getById(userId);
      result.put("code", user == null ? "1" : "0");
      result.put("userInfo", user);
      return result;
    }

    result = code2Session(code);
    String openId = result.getString("openid");
    if (StrUtil.isNotBlank(openId)) {
      // 如果已存在该用户则直接返回
      User user = userService.getByOpenId(openId);
      if (user != null) {
        result.put("code", "0");
        result.put("userInfo", user);
      } else {
        result.put("code", "1");
      }
      return result;
    }
    result.put("code", "-1");
    return result;
  }


  @Override
  public JSONObject login(JSONObject json) {
    JSONObject result = getUserInfo(json);
    String openId = json.getString("openid");
    User user = userService.getByOpenId(openId);
    if (user != null) {
      result.put("code", "0");
      result.put("userInfo", user);
      return result;
    } else {
      result.put("code", "-1");
      return result;
    }
  }
}
